import { Button, Form, Input, Modal, message, Row, Col } from 'antd';
import request from '@/utils/request';
import React, { forwardRef, useEffect, useImperativeHandle, useState, useCallback } from 'react';
import { useAiTextEditor } from '@/pages/marketing/aiText/AiTextEditor';
import styles from './style.less';


interface IRef {
  edit?: () => any;
  callback?: () => any;
}

export async function addRule(data: object) {
  return request('/api/merchant/notice', {
    method: 'POST',
    data,
  });
}


const AddModal: React.ForwardRefRenderFunction<IRef, any> = (props, ref) => {

  const [text, setText] = useState('');

  const { sendMessage, text: dt, loading } = useAiTextEditor({
    isBr: false
  })
  const handleGen = useCallback(() => {
    sendMessage(text)
  }, [text])

  useEffect(() => {
    form.setFieldsValue({ content: dt });
  }, [dt])

  const [form] = Form.useForm();
  const [modalVisible, setModalVisible] = useState(false);
  const [btnLoading, setBtnLoading] = useState<boolean>(false);
  const [editRow, setEditRow] = useState<any>(null);

  const { callback } = props;

  /**
 * 添加节点
 * @param fields
 */
  const updateItem = async (fields: any, id: any) => {
    setBtnLoading(true);
    const isAdd = !id;
    const txt = isAdd ? '添加' : '编辑';
    const params = { ...fields };
    if (!isAdd) {
      Object.assign(params, { id });
    }
    try {
      if (isAdd) {
        await addRule(params);
      }
    } catch (error) {
      message.error(`${txt}失败请重试！`);
      return false;
    } finally {
      setBtnLoading(false)
    }
  };


  const handleCancel = () => {
    setModalVisible(false);
    form.resetFields(['name', 'config']);
  };

  const getInitialValues = async (row: any) => {
    if (row?.id) form.setFieldsValue(row);
  };

  // 关闭弹窗 去掉loading
  useEffect(() => {
    if (!modalVisible) setBtnLoading(false);
  }, [modalVisible]);

  useImperativeHandle(ref, () => ({
    edit: (row?: any) => {
      setEditRow(row);
      if (row) getInitialValues(row);
      setModalVisible(true);
    }
  }));

  const handleOk = () => {
    console.log(111);
    form.validateFields().then((data) => {
      Object.assign(data, {
        status: 0
      })
      updateItem(data, editRow?.id).then(() => {
        setModalVisible(false);
        callback?.();
      });
    })
  };

  return (
    <>
      <Modal
        title={
          editRow
            ? '编辑公告'
            : '新增公告'
        }
        onCancel={handleCancel}
        onOk={handleOk}
        visible={modalVisible}
        width={640}
        maskClosable={false}
        okButtonProps={{
          loading: btnLoading
        }}
      >
        <Form form={form} labelCol={{ span: 4 }} wrapperCol={{ span: 16 }} >
          <Form.Item label="公告名称" name="name" required rules={[{ required: true, message: '公告名称不能为空' }]}>
            <Input />
          </Form.Item>
          <Form.Item label="AI文案生成器" >
            <div className={styles['ai_content']}>
              <Input.TextArea style={{ width: 300 }} value={text} onChange={(v) => setText(v.target.value)} placeholder='输入你想发布的内容，智能帮你生成专业的公告内容' />
              <Button type='primary' onClick={handleGen} loading={loading}>确定</Button>
            </div>
          </Form.Item>
          <Form.Item label="公告内容" name="content" initialValue={''} required rules={[{ required: true, message: '公告内容不能为空' }]}>
            <Input.TextArea style={{ height: 400 }} />
          </Form.Item>
        </Form>
      </Modal>
    </>
  );
};

export default forwardRef(AddModal);
